package cn.com.dhcc.app.pub.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件压缩
 * @日期 2016-4-28  上午10:59:32
 * @作者 macky_he
 * @版本 [地下水V1.0]
 */
public class FileZip {
	/**
	 * 
	 * @param srcfile
	 *            文件名数组
	 * @param zipfile
	 *            压缩后文件
	 * @throws Exception 
	 */
	public static void ZipFiles(File[] srcfile, File zipfile) throws Exception {
		byte[] buf = new byte[1024];
		ZipOutputStream out = null;
		try {
			out = new ZipOutputStream(new FileOutputStream(
					zipfile));
			for (int i = 0; i < srcfile.length; i++) {
				FileInputStream in = new FileInputStream(srcfile[i]);
				//加上System.currentTimeMillis()防止文件名冲突，导致文件不能完整的压缩
				out.putNextEntry(new ZipEntry( srcfile[i].getName()));
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
			}
		} catch (IOException e) {
			throw new Exception("压缩文件发生异常", e);
		} finally {
			out.close();
		}
	}
}
